﻿using System;
using System.Collections.Generic;
using TB;
using Swift;
using Utils;

namespace Nova
{
    public static class AIExt
    {
        public static StateMachineManager SMMgr = null;

        public static StateMachine CreateAI(this Actor actor, string ai)
        {
            switch (ai)
            {
                case "e1":
                    break;
            }

            return null;
        }

        // 获取角色当前状态机
        public static StateMachine GetAIStateMachine(this Actor a) {
            return SMMgr.Get (a.UID);
        }

        // 创建新的状态机
        public static StateMachine CreateNewStateMachine(this Actor a) {
            SMMgr.Del (a.UID);
            return SMMgr.Get (a.UID);
        }

        // 启动状态机
        public static void StartAI(this Actor a) {
            // 还没创建就先创建一个
            var sm = a.GetAIStateMachine ();
            if(sm == null) {
                sm = a.CreateAI (a.AI);
            }

            if(sm != null)
                sm.StartAt ();
        }

        // 停止状态机
        public static void StopAI(this Actor a) {
            var sm = a.GetAIStateMachine ();
            if(sm != null)
                sm.Destroy ();

            SMMgr.Del (a.UID);
        }

        static StateMachine MakeSureSM(this Actor a) {
            var sm = a.GetAIStateMachine ();
            if(sm == null) {
                sm = new StateMachine (a.UID);
                SMMgr.Add (sm);
            }

            return sm;
        }



        //public static StateMachine ChangeDirWhenHit(this Actor a) {

        //    var sm = a.MakeSureSM ();

        //    sm.NewState ("GoAhead").Run ((state, te) => {

        //        a.Move (0.5f / a.Speed);

        //    }).AsDefault ();

        //    sm.NewState ("ChangeDir").Run ((state, te) => {

        //        int dir = RandomUtils.Random (0, 4);
        //        a.Dir = (DIR) dir;

        //    });

        //    sm.Trans ().From ("GoAhead").To ("ChangeDir").When (state => {

        //        return true;
        //    });

        //    return sm;
        //}


        #region 状态迁移条件

        // 等待指定时间
        public static StateTransition Wait4Sec(this StateTransition st, float sec)
        {
            float t = sec;
            st.When(state => { return t <= 0; })
              .OnReset(() => { t = sec; })
              .OnTimeElapsed((te) => { t -= te; });

            return st;
        }

        #endregion
    }
}
